package cn.znzz.cjm.pay.controller;


import cn.znzz.cjm.order.domain.AdoptOrder;
import cn.znzz.cjm.order.domain.ProductOrder;
import cn.znzz.cjm.order.service.IAdoptOrderService;
import cn.znzz.cjm.order.service.IProductOrderService;
import cn.znzz.cjm.pay.config.AlipayConfig;
import cn.znzz.cjm.pay.constants.PayConstants;
import cn.znzz.cjm.pay.domain.AlipayInfo;
import cn.znzz.cjm.pay.domain.PayBill;
import cn.znzz.cjm.pay.service.IAlipayInfoService;
import cn.znzz.cjm.pay.service.IPayBillService;
import cn.znzz.cjm.quartz.constant.JobTypeConstants;
import cn.znzz.cjm.quartz.service.IQuartzService;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IAdoptOrderService adoptOrderService;
    @Autowired
    private IProductOrderService productOrderService;
    @Autowired
    private IQuartzService quartzService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request){
        //获取支付宝POST过来反馈信息
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                params.put(name, valueStr);
            }

            String unionPaySn = params.get("out_trade_no");
            PayBill payBill = payBillService.loadByUnionPaySn(unionPaySn);
            if(payBill!=null){
                Long shop_id = payBill.getShop_id();
                AlipayInfo info = alipayInfoService.getByShopId(shop_id);
                boolean signVerified = AlipaySignature.rsaCheckV1(params,
                        info.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名

                if(signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no =request.getParameter("out_trade_no");

                    //支付宝交易号
                    String trade_no =request.getParameter("trade_no");

                    //交易状态
                    String trade_status = request.getParameter("trade_status");
                    System.out.println("哈哈哈哈");
                    if(trade_status.equals("TRADE_FINISHED")){

                    }else if (trade_status.equals("TRADE_SUCCESS")){
                        //修改支付单状态，已经支付
                        payBill.setState(1);

                        payBill.setUpdateTime(new Date());
                        //纪录支付流水
                        if(PayConstants.BUSINESS_TYPE_ADOPT.equals(payBill.getBusinessType())){
                            //领养订单
                            AdoptOrder adoptOrder=adoptOrderService.queryById(payBill.getBusinessKey());
                            System.out.println(adoptOrder.getId());
                            adoptOrder.setState(1);
                            adoptOrderService.update(adoptOrder);
                            System.out.println(adoptOrder.getState());
                            //查询业务订单，修改状态
                            //杀死支付超时的定时器
                            String jobName= JobTypeConstants.TIME_OUT_ADOPT_LAST_PAY+adoptOrder.getId();
                            quartzService.removeJob(jobName);
                        }else if(PayConstants.BUSINESS_TYPE_PRODUCT.equals(payBill.getBusinessType())){
                            //领养订单
                            ProductOrder productOrder=productOrderService.queryById(payBill.getBusinessKey());
                            System.out.println(productOrder.getId());
                            productOrder.setState(1);
                            productOrderService.update(productOrder);
                            System.out.println(productOrder.getState());
                            //查询业务订单，修改状态
                            //杀死支付超时的定时器
                            String jobName= JobTypeConstants.TIME_OUT_PRODUCTS_LAST_PAY+productOrder.getId();
                            quartzService.removeJob(jobName);
                        }
                    }

                }else {//验证失败
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
